import json
import uuid

from mainapp import app
from mainapp.schemas import SysUserLoginSchema

from fastapi import Body,Path,Query, Depends
from dbs.admindao import AdminDao
from dbs.caches import *
from utils.crypt import hash_data

@app.post('/login')
def admin_login(data: SysUserLoginSchema = Body(...)):
    dao = AdminDao()
    print('---->', hash_data(data.password))
    ret = dao.login(name=data.username, pwd=hash_data(data.password))
    if not ret:
        return {'status':1,'msg': '用户名或密码不正确'}

    role_id = ret.pop('role_id')
    role = dao.get_role(role_id)
    if not role['code'].startswith('sys'):
        permissions = dao.get_permissions(role_id)
        role['permissions'] = permissions

    ret['role'] = role
    # 任务：写入到缓存中，生成一个token, 存储ret字典序列化的字符串
    token = uuid.uuid4().hex
    save_token(token, json.dumps(ret))
    return {
        'status': 0,
        'data': ret,
        'token': token
    }
